import React from 'react';
import {
    AreaChart,
    Area,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    PieChart,
    Pie,
    Legend,
    Cell,
    ResponsiveContainer
} from 'recharts';
import {Link} from 'react-router';
import {Icon} from 'antd';
import config from '../../config';
import {getChartData} from '../../utils';
import {FETCH_ORG_DATA} from '../../constants/actTypes';


/**
 * 加载公共组件
 * */
import MainSection from '../../components/MainSection/MainSection';
import NoData from '../../components/NoData/NoData';


/**
 * 加载样式或图片文件
 * */
import './sass/chart.scss';
import actIcon from './images/act.png';
import joinIcon from './images/join.png';
import fansIcon from './images/fans.png';
import pieIcon from './images/pie.png';

class Org extends React.Component {
    constructor(props) {
        super(props);
        this.renderLabel = this.renderLabel.bind(this);
        this.renderTimeBtn = this.renderTimeBtn.bind(this);
        this.renderLineChart = this.renderLineChart.bind(this);
        this.renderChildChart = this.renderChildChart.bind(this);
        this.state = {
            curTab: 0,
            org: {
                activityAmount: 0,
                followerAmount: 0,
                attenderAmount: 0,
                events: [],
                pays: [],
                signs: [],
                relations: []

            },
            actData: [],
            actData90: [],
            applyData: [],
            applyData90: [],
            signData: [],
            signData90: [],
            childData: [],
            adultData: [],

            actTime: 7,
            applyTime: 7,
            signTime: 7,
            childTime: 7,
            adultTime: 7

        };
    }

    componentDidMount() {
        const {actions, location, act} = this.props;
        let orgId = location.query.id;
        if (!orgId) {
            alert('未选择场馆');
            return false;
        }
        actions.fetchOrgData({organizeId: orgId}).then(res => {
            if(res.type===FETCH_ORG_DATA){
                if (res.data.code === 20000) {
                    let org = res.data.data;
                    let events = org.activitys;
                    let pays = org.pays;
                    let signs = org.signs;
                    let role = org.relations;

                    let actData90 = getChartData(events, "活动数");
                    let applyData90 = getChartData(pays, "报名数");
                    let signData90 = getChartData(signs, "签到数");

                    this.setState({
                        org: org,
                        actData90: actData90,
                        role: role,
                        applyData90: applyData90,
                        signData90: signData90
                    }, ()=> {
                        this.handleFetchData(7, 'act');
                        this.handleFetchData(7, 'apply');
                        this.handleFetchData(7, 'sign');
                        this.handleFetchData(7, 'child');
                        this.handleFetchData(7, 'adult');
                    });


                } else {
                    alert(res.data.message)
                }
            }

        });
    }

    handleChangeTab(index) {
        this.setState({
            curTab: index
        })
    }

    handleFetchData(day, type) {
        if (type === 'act') {
            this.setState({
                actTime: day,
                actData: (this.state.actData90).slice(0, day).reverse()
            })
        } else if (type === 'apply') {
            this.setState({
                applyTime: day,
                applyData: (this.state.applyData90).slice(0, day).reverse()
            })
        } else if (type === 'sign') {
            this.setState({
                signTime: day,
                signData: (this.state.signData90).slice(0, day).reverse()
            })
        } else if (type === 'child') {
            let index = 0;
            if (day === 30) {
                index = 1;
            } else if (day === 90) {
                index = 2;
            }
            let data = [
                {name: '男孩', value: this.state.role[index][1]},
                {name: '女孩', value: this.state.role[index][2]}];
            this.setState({
                childTime: day,
                childData: data.filter((v)=> v.value > 0)
            })
        } else if (type === 'adult') {
            let index = 0;
            if (day === 30) {
                index = 1;
            } else if (day === 90) {
                index = 2;
            }
            let data = [
                {name: '爸爸', value: this.state.role[index][3]},
                {name: '妈妈', value: this.state.role[index][4]},
                {name: '爷爷', value: this.state.role[index][5]},
                {name: '奶奶', value: this.state.role[index][6]},
                {name: '外公', value: this.state.role[index][7]},
                {name: '外婆', value: this.state.role[index][8]},
                {name: '其他', value: this.state.role[index][0]}];

            this.setState({
                adultTime: day,
                adultData: data.filter((v)=> v.value > 0)
            })
        }
    }

    renderTimeBtn(type) {
        return (
            <div className="btn-group">
                <button className={this.state[type+'Time'] === 7 ? 'cur' : ''}
                        onClick={this.handleFetchData.bind(this,7,type)}>近一周
                </button>
                <button className={this.state[type+'Time'] === 30 ? 'cur' : ''}
                        onClick={this.handleFetchData.bind(this,30,type)}>近一月
                </button>
                <button className={this.state[type+'Time'] === 90 ? 'cur' : ''}
                        onClick={this.handleFetchData.bind(this,90,type)}>近三月
                </button>
            </div>
        )
    }

    renderLineChart(type) {
        let data = [];
        let dataKey = '';
        switch (type) {
            case 'act':
                data = this.state.actData;
                dataKey = '活动数';
                break;
            case 'apply':
                data = this.state.applyData;
                dataKey = '报名数';
                break;
            case 'sign':
                data = this.state.signData;
                dataKey = '签到数';
                break;
            default:

        }
        return (
            <div className="line-container">
                {
                    !!data.length ? (
                        <ResponsiveContainer width="100%" height="100%">
                            <AreaChart data={data}
                                       margin={{top: 0, right: 40, left: -25, bottom: 0}}>
                                <XAxis dataKey="name"/>
                                <YAxis/>
                                <CartesianGrid strokeDasharray="3 3"/>
                                <Tooltip/>
                                <Area type='monotone' dataKey={dataKey} stackId="1"
                                      stroke='#00afeb'
                                      fillOpacity={.2}
                                      fill='#00afeb'/>
                            </AreaChart>
                        </ResponsiveContainer>
                    ) : <NoData/>
                }
            </div>

        )
    }

    renderLabel(props) {
        const RADIAN = Math.PI / 180;
        const {
            cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle,
            fill, payload, percent, value
        } = props;
        const radius = innerRadius + (outerRadius - innerRadius) * 2.5;
        const x = cx + radius * Math.cos(-midAngle * RADIAN);
        const y = cy + radius * Math.sin(-midAngle * RADIAN);
        const sin = Math.sin(-RADIAN * midAngle);
        const cos = Math.cos(-RADIAN * midAngle);
        const sx = cx + (outerRadius + 10) * cos;
        const sy = cy + (outerRadius + 10) * sin;
        const mx = cx + (outerRadius + 20) * cos;
        const my = cy + (outerRadius + 20) * sin;
        const ex = mx + (cos >= 0 ? 1 : -1) * 22;
        const ey = my;
        const textAnchor = cos >= 0 ? 'start' : 'end';

        return (
            <g>
                <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none"/>
                <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none"/>
                <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} fill="#333" textAnchor={textAnchor}>
                    {
                        payload.name
                    }
                </text>
                <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} dy={18} fill="#333" textAnchor={textAnchor} className="fs-36">
                    {
                        (percent * 100).toFixed(0)
                    }
                    %
                </text>

            </g>

        );
    }

    renderChildChart() {
        let colors = ['#74b1f9', '#ed5063'];
        let data = this.state.childData;
        return (
            <div className="pie-container">
                {
                    !!data.length ? (
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie data={data}
                                     dataKey="value"
                                    // activeIndex={0}
                                    // activeShape={this.renderActiveShape}
                                    //  cx={160}
                                    //  cy={160}
                                     innerRadius={40}
                                     outerRadius={70}
                                     fill="#82ca9d"
                                     label={this.renderLabel}
                                >
                                    {
                                        data.map((item, index) => (
                                            <Cell key={`cell-${index}`} fill={colors[index]}/>
                                        ))
                                    }
                                </Pie>
                            </PieChart>
                        </ResponsiveContainer>
                    ) : <NoData/>
                }
            </div>

        )
    }

    renderAdultChart() {
        let colors = ['#ff6601', '#ed5063', '#f6a623', '#54cd6a', '#24d4ac', '#74b1f9', '#be55db'];
        let data = this.state.adultData;
        return (
            <div className="pie-container">
                {
                    !!data.length ? (
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie data={data}
                                     dataKey="value"
                                    // activeIndex={0}
                                    // activeShape={this.renderActiveShape}
                                    //  cx={160}
                                    //  cy={160}
                                     innerRadius={40}
                                     outerRadius={70}
                                     fill="#82ca9d"
                                     label={this.renderLabel}
                                >
                                    {
                                        data.map((item, index) => (
                                            <Cell key={`cell-${index}`} fill={colors[index]}/>
                                        ))
                                    }
                                </Pie>
                            </PieChart>
                        </ResponsiveContainer>
                    ) : <NoData/>
                }
            </div>


        )
    }


    render() {
        const {act} = this.props;
        let org = this.state.org;
        return (
            <MainSection className="chart" title="数据详情">

                <div className="org-head">
                    <ul className="row">
                        <li>
                            <p>{org.activityAmount}</p>
                            <p><img src={actIcon}/>活动总数</p>
                        </li>
                        <li>
                            <p>{org.followerAmount}</p>
                            <p><img src={fansIcon}/>粉丝总数</p>
                        </li>
                        <li>
                            <p>{org.attenderAmount}</p>
                            <p><img src={joinIcon}/>总参与人数</p>
                        </li>
                    </ul>
                </div>

                <div className="org-tabs">
                    <div className="tab-btn">
                        <span key="0" className={"tab-item " + (this.state.curTab === 0 ? "cur" : "")}
                              onClick={this.handleChangeTab.bind(this,0)}>活动数据</span>
                        <span key="1" className={"tab-item " + (this.state.curTab === 1 ? "cur" : "")}
                              onClick={this.handleChangeTab.bind(this,1)}>报名数据 </span>
                        <span key="2" className={"tab-item " + (this.state.curTab === 2 ? "cur" : "")}
                              onClick={this.handleChangeTab.bind(this,2)}>签到数据</span>
                    </div>
                    <div className={this.state.curTab === 0 ? "tab-content" : "tab-content hide"}>
                        {
                            this.renderLineChart('act')
                        }

                        {
                            this.renderTimeBtn('act')
                        }

                    </div>
                    <div className={this.state.curTab === 1 ? "tab-content" : "tab-content hide"}>
                        {
                            this.renderLineChart('apply')
                        }

                        {
                            this.renderTimeBtn('apply')
                        }
                    </div>
                    <div className={this.state.curTab === 2 ? "tab-content" : "tab-content hide"}>
                        {
                            this.renderLineChart('sign')
                        }

                        {
                            this.renderTimeBtn('sign')
                        }
                    </div>

                </div>

                <div className="org-pie">
                    <h5><img src={pieIcon}/>儿童占比</h5>
                    {
                        this.renderChildChart()
                    }
                    {
                        this.renderTimeBtn('child')
                    }
                </div>
                <div className="org-pie">
                    <h5><img src={pieIcon}/>家长占比</h5>
                    {
                        this.renderAdultChart()
                    }
                    {
                        this.renderTimeBtn('adult')
                    }
                </div>

            </MainSection>
        );
    }
}

export default Org;